from scipy import sparse
from scipy.cluster.vq import kmeans, vq, whiten

class Clusters(object):
    MAX_NB_CLUSTERS = 10
    NB_ITERATIONS = 20
    THRESHOLD = 1.0000000000000001e-05
    
    def __init__(self, matrixFreq):
        self.positions = {}
        self.cat2clus = {}
        self.codes = self.getCodes(matrixFreq)
        self.clusteredMatrix = self.rebuildMatrix(matrixFreq)

        
    def getCodes(self, matrixFreq):
        whitened = whiten(matrixFreq)
        km = kmeans(whitened, Clusters.MAX_NB_CLUSTERS, Clusters.NB_ITERATIONS, Clusters.THRESHOLD)
        self.nbClusters = km[0].__len__()
        quantifiedVector = vq(whitened, km[0])
        return quantifiedVector[0]
        
    
    def rebuildMatrix(self, matrixFreq):
        reMatrix = sparse.lil_matrix((self.nbClusters, matrixFreq.shape[1]))
        
        for i in range(self.codes.__len__()):
            j = self.codes[i]
            self.cat2clus[i] = j
            if self.positions.has_key(j):
                self.positions[j].append(i)
            else:
                self.positions[j] = [i]
                    
        for i in range(self.nbClusters):
            for j in self.positions[i]:
                reMatrix[i,:] += matrixFreq[j,:]            
        return reMatrix            
